package com.android.losscheck;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import com.android.losscheck.R;
import com.android.losscheck.bean.MyWebServiceHelper;
import com.android.losscheck.bean.User;

import com.tencent.bugly.crashreport.CrashReport;



import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Paint;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class LoginActivity extends Activity implements OnClickListener {
	private String name;
	private String userid;
	private String userpwd;
	private String userflag;
	private EditText username;
	private EditText password;
	private ProgressBar progress;
	private String org;
	private CatchExcep application;  
	
	//检测新版本
	private final String TAG = this.getClass().getName();
	private int UPDATA_NONEED_AUTO = 0;
	private final int UPDATA_NONEED = 0;
	private final int UPDATA_CLIENT = 1;
	private final int GET_UNDATAINFO_ERROR = 2;
	private final int SDCARD_NOMOUNTED = 3;
	private final int DOWN_ERROR = 4;
	private Button getVersion;
	private UpdataInfo info;
	private String localVersion;
	
	public static MyWebServiceHelper myweb;
	public static String ips,namespace_hello,wsdl_hello,wsdl_iuser,wsdl_ilocation,wsdl_iopreationtype,wsdl_imaterial,wsdl_irefr_inout_results,wsdl_irefr_approve_status,wsdl_irefr_send_info,wsdl_icommon,wsdl_irefr_inspect_results;
	// 查询表名为“User”的所有内容
//	private final static String sql = "SELECT DISTINCT user_id,user_name,password,role_id,use_flag,create_user,Create_time FROM Refr_User_Info";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);

		//Bugly
//    	CrashReport.initCrashReport(this, "900012412", false);	       
//		CrashReport.setUserSceneTag(this, 4806); // 上报后的Crash会显示该标签    
		 application = (CatchExcep)getApplication();  
	        application.init(getApplicationContext());  
		
		username = (EditText) findViewById(R.id.username_input);
		password = (EditText) findViewById(R.id.password_input);
		progress = (ProgressBar) findViewById(R.id.progress);
		findViewById(R.id.but_login).setOnClickListener(this);
		findViewById(R.id.but_clear).setOnClickListener(this);
		findViewById(R.id.checknew).setOnClickListener(this);
//		findViewById(R.id.but_close).setOnClickListener(this);
		TextView text = (TextView) findViewById(R.id.getcon);
		text.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
		text.setClickable(true);
		text.setFocusable(true);
		text.setOnClickListener(this);


		Intent serviceIntent = new Intent(LoginActivity.this, ReqService.class);
		startService(serviceIntent);
		myweb=new MyWebServiceHelper();
	
//		getSysConfig();
		
		
		try {
			localVersion = getVersionName();
			TextView tver=(TextView)findViewById(R.id.txtVer);
			tver.setText("V"+localVersion);
			UPDATA_NONEED_AUTO=1;
			CheckVersionTask cv = new CheckVersionTask();
			new Thread(cv).start();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	

	}
	
	/**
	 * 获取配置信息
	 */
	private void getSysConfig()
	{
		SharedPreferences sps = getSharedPreferences("servers", MODE_PRIVATE);	
		ips= sps.getString("ip", null);
		
		wsdl_hello= sps.getString("wsdl_hello", null);
		namespace_hello= sps.getString("namespace_hello", null);
		
		wsdl_iuser= sps.getString("wsdl_iuser", null);
		wsdl_ilocation= sps.getString("wsdl_ilocation", null);
		wsdl_iopreationtype= sps.getString("wsdl_iopreationtype", null);
		wsdl_imaterial= sps.getString("wsdl_imaterial", null);
		wsdl_irefr_inout_results= sps.getString("wsdl_irefr_inout_results", null);
		wsdl_irefr_approve_status= sps.getString("wsdl_irefr_approve_status", null);
		wsdl_irefr_send_info= sps.getString("wsdl_irefr_send_info", null);
		wsdl_icommon= sps.getString("wsdl_icommon", null);
		wsdl_irefr_inspect_results= sps.getString("wsdl_irefr_inspect_results", null);
//		Log.d("login", "WSDL:"+WSDL+" targetNameSpace:"+targetNameSpace);
	}
	
	
	private void updateStatus() {

		try {
			myweb.modiUserStatus(1,userid,	wsdl_iuser);
			
		} catch (Exception e) {

			e.printStackTrace();
		} finally {
			
		}

	}
	
	
	
	/**
	 * @param txtName
	 * @param txtPwd
	 * @return 登陆结果 登陆
	 */
	public void login(String WSDL) {
			
		List<User>rs= myweb.getAllUsers(WSDL);		
		try {
			if (rs != null) {
				Log.e(TAG, "开始登陆");

				for(int i=0;i<rs.size();i++)
				{
					User u=(User)rs.get(i);
					 Log.e(TAG, "开始验证");
					name = u.getUser_name();
					userid = u.getUser_id();
					userpwd = u.getPassword();
					userflag = u.getUse_flag();
					 Log.e(TAG,"name:"+name+" userid:"+userid+" userpwd:"+userpwd+" userflag:"+userflag);
					
					if (username.getText().toString().trim()	.equals(userid)&& password.getText().toString().trim().equals(userpwd)) 
					{
						if ("N".equals(userflag))
						{
							mHandler.sendMessage(Message.obtain(mHandler, 1));
							return;
						} else {
							mHandler.sendMessage(Message.obtain(mHandler, 0));
							return;
						}
					} else if (i==rs.size()-1) {
						mHandler.sendMessage(Message.obtain(mHandler, -1));

					}

				}
			
			} else {
				Log.e("loginActivity", "here");
				mHandler.sendMessage(Message.obtain(mHandler, -2));
			}
		} catch (Exception e) {
			e.printStackTrace();
			mHandler.sendMessage(Message.obtain(mHandler, -3));
			System.out.println(e.getMessage().toString());
		} finally {

		}
	}


	Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			progress.setVisibility(View.GONE);
			switch (msg.what) {
			case 0:
				Intent intent = new Intent(LoginActivity.this,
						MainActivity.class);
				intent.putExtra("user_name", name);
//				intent.putExtra("Org_Code", org);
				intent.putExtra("user_id", userid);
				intent.putExtra("user_pwd", userpwd);
				intent.putExtra("user_flag", userflag);

//				Log.d("made", org);
				startActivity(intent);
				LoginActivity.this.finish();
				Toast.makeText(LoginActivity.this, "恭喜,登录成功", Toast.LENGTH_LONG)
						.show();
				new Thread(new Runnable() {

					@Override
					public void run() {
						updateStatus();
					}
				}).start();
				break;
			case 1:
				Toast.makeText(LoginActivity.this, "此用户已被注销", Toast.LENGTH_LONG)
						.show();
				break;
			case -1:
				Toast.makeText(LoginActivity.this, "用户名/密码不存在，请重新输入",
						Toast.LENGTH_LONG).show();
				break;
			case -2:
				Toast.makeText(LoginActivity.this, "连接服务器失败", Toast.LENGTH_LONG)
						.show();

				break;
			case -3:
				Toast.makeText(LoginActivity.this, "连接服务器异常", Toast.LENGTH_LONG)
						.show();
				break;
			default:
				break;
			}

		}

	};

	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		if (ev.getAction() == MotionEvent.ACTION_DOWN) {
			// 获得当前得到焦点的View
			View v = getCurrentFocus();
			if (v != null && (v instanceof EditText)) {
				int[] l = { 0, 0 };
				v.getLocationInWindow(l);
				int left = l[0], top = l[1], bottom = top + v.getHeight(), right = left
						+ v.getWidth();
				if (ev.getX() > left && ev.getX() < right && ev.getY() > top
						&& ev.getY() < bottom) {
					// 点击EditText的事件，忽略
				} else if (v.getWindowToken() != null) {
					((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE))
							.hideSoftInputFromWindow(v.getWindowToken(),
									InputMethodManager.HIDE_NOT_ALWAYS);
				}
			}
		}
		return super.dispatchTouchEvent(ev);
	}
	

	
	private void ExitApp()
	{
		new com.zf.iosdialog.widget.AlertDialog(this).builder().setTitle("温馨提示")
		.setMsg("确认要退出吗？")
		.setPositiveButton("确认退出", new OnClickListener() {
			@Override
			public void onClick(View v) {
				
//				new Thread(new Runnable() {
					
//					@Override
//					public void run() {
//						updateStatus(ConnDB.handle());
//					}
//				}).start(); 
//				 application.finishActivity();  
				application.finishActivity(0);  
				LoginActivity.this.finish(); 
//				android.os.Process.killProcess(android.os.Process.myPid());    
//				application.finishActivity();  
	            
	           
	            
			}
		}).setNegativeButton("取消", new OnClickListener() {
			@Override
			public void onClick(View v) {
				
			}
		}).show();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.but_login:
			getSysConfig();
			if (username.getText().length() == 0
					|| "".equals(username.getText().toString().trim())
					|| password.getText().length() == 0
					|| "".equals(password.getText().toString().trim())) {
				Toast.makeText(LoginActivity.this, "用户名/密码不能为空",
						Toast.LENGTH_SHORT).show();

			} else if (	wsdl_iuser==null ) {
				Toast.makeText(this, "请先设置服务器属性", 3000).show();
			} else {
				progress.setVisibility(View.VISIBLE);
				
				new Thread(new Runnable() {
					@Override
					public void run() {
						login(wsdl_iuser);
					}	
				}).start();
			}
			break;
		case R.id.getcon:
			startActivity(new Intent(this, GetSysConfigActivity.class));
			break;
		case R.id.but_clear:
			username.setText("");
			password.setText("");
			break;
		case R.id.checknew:
			try {
				localVersion = getVersionName();
				UPDATA_NONEED_AUTO=0;
				CheckVersionTask cv = new CheckVersionTask();
				new Thread(cv).start();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;
		default:
			break;
		}
	}
	
	

	private String getVersionName() throws Exception {
		//getPackageName()是你当前类的包名，0代表是获取版本信息  
		PackageManager packageManager = getPackageManager();
		PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(),
				0);
		return packInfo.versionName;
	}
	public class CheckVersionTask implements Runnable {
		InputStream is;
		public void run() {
			try {
				getSysConfig();
				
				String path = "http://"+ips+"/android/version.xml";//getResources().getString(R.string.up_server);
				URL url = new URL(path);
				HttpURLConnection conn = (HttpURLConnection) url
						.openConnection();
				conn.setConnectTimeout(5000);
				conn.setRequestMethod("GET"); 
                int responseCode = conn.getResponseCode(); 
                if (responseCode == 200) { 
                    // 从服务器获得一个输入流 
                	is = conn.getInputStream(); 
                } 
				info = UpdataInfoParser.getUpdataInfo(is);
				if (info.getVersion().equals(localVersion)) {
					Log.i(TAG, "版本号相同");
					Message msg = new Message();
					msg.what = UPDATA_NONEED;
					handler.sendMessage(msg);
					// LoginMain();
				} else {
					Log.i(TAG, "版本号不相同 ");
					Message msg = new Message();
					msg.what = UPDATA_CLIENT;
					handler.sendMessage(msg);
				}
			} catch (Exception e) {
				Message msg = new Message();
				msg.what = GET_UNDATAINFO_ERROR;
				handler.sendMessage(msg);
				e.printStackTrace();
			}
		}
	}
	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			case UPDATA_NONEED:
				if(UPDATA_NONEED_AUTO<=0)
				{
					Toast.makeText(getApplicationContext(), "不需要更新",
							Toast.LENGTH_SHORT).show();
				}
				break;
			case UPDATA_CLIENT:
				 //对话框通知用户升级程序   
				showUpdataDialog();
				break;
			case GET_UNDATAINFO_ERROR:
				//服务器超时   
	            Toast.makeText(getApplicationContext(), "获取服务器更新信息失败", 1).show(); 
				break;
			case DOWN_ERROR:
				//下载apk失败  
	            Toast.makeText(getApplicationContext(), "下载新版本失败", 1).show(); 
				break;
			}
		}
	};
	
	public boolean onKeyDown(int keyCode, KeyEvent event) { 
		if ((keyCode == KeyEvent.KEYCODE_BACK)) { 
			ExitApp();
//			new com.zf.iosdialog.widget.AlertDialog(this).builder().setTitle("温馨提示")
//			.setMsg("确认要退出吗？")
//			.setPositiveButton("确认退出", new OnClickListener() {
//				@Override
//				public void onClick(View v) {
//					
////					new Thread(new Runnable() {
//						
////						@Override
////						public void run() {
////							updateStatus(ConnDB.handle());
////						}
////					}).start(); 
////					 application.finishActivity();  
//					
//		            LoginActivity.this.finish(); 
//		          
//		           
//				
//				}
//			}).setNegativeButton("取消", new OnClickListener() {
//				@Override
//				public void onClick(View v) {
//					
//				}
//			}).show();
		}
			
		
		return false;
	}
	/* 
	 *  
	 * 弹出对话框通知用户更新程序  
	 *  
	 * 弹出对话框的步骤： 
	 *  1.创建alertDialog的builder.   
	 *  2.要给builder设置属性, 对话框的内容,样式,按钮 
	 *  3.通过builder 创建一个对话框 
	 *  4.对话框show()出来   
	 */  
	protected void showUpdataDialog() {
		
		new com.zf.iosdialog.widget.AlertDialog(this).builder().setTitle("软件版本更新")
		.setMsg(info.getDescription())
		.setPositiveButton("确定", new OnClickListener() {
			@Override
			public void onClick(View v) {
				Log.i(TAG, "下载apk,更新");
				downLoadApk();
			}
		}).setNegativeButton("取消", new OnClickListener() {
			@Override
			public void onClick(View v) {

			}
		}).show();
	}
	/* 
	 * 从服务器中下载APK 
	 */  
	protected void downLoadApk() {  
	    final ProgressDialog pd;    //进度条对话框  
	    pd = new  ProgressDialog(this);  
	    pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);  
	    pd.setMessage("正在下载更新");  
	    pd.show();  
	    new Thread(){  
	        @Override  
	        public void run() {  
	            try {  
	                File file = DownLoadManager.getFileFromServer(info.getUrl(), pd);  
	                sleep(3000);  
	                installApk(file);  
	                pd.dismiss(); //结束掉进度条对话框  
	            } catch (Exception e) {  
	                Message msg = new Message();  
	                msg.what = DOWN_ERROR;  
	                handler.sendMessage(msg);  
	                e.printStackTrace();  
	            }  
	        }}.start();  
	}  
	  
	//安装apk   
	protected void installApk(File file) {  
	    Intent intent = new Intent();  
	    //执行动作  
	    intent.setAction(Intent.ACTION_VIEW);  
	    //执行的数据类型  
	    intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");  
	    startActivity(intent);  
	}  

}

